<template>
    <div class="kline-chart-div">
        <div ref="chartEl" class="container">


        </div>
    </div>

</template>


<script>
import echarts from 'echarts';

var upColor = '#ec0000';
var downColor = '#00da3c';

function splitData(rawData) {
    var categoryData = [];
    var values = [];
    var volumes = [];
    for (var i = 0; i < rawData.length; i++) {
        categoryData.push(rawData[i].splice(0, 1)[0]);
        values.push(rawData[i]);
        volumes.push([i, rawData[i][4], rawData[i][0] > rawData[i][1] ? 1 : -1]);
    }

    return {
        categoryData: categoryData,
        values: values,
        volumes: volumes
    };
}

function calculateMA(dayCount, data) {
    var result = [];
    for (var i = 0, len = data.values.length; i < len; i++) {
        if (i < dayCount) {
            result.push('-');
            continue;
        }
        var sum = 0;
        for (var j = 0; j < dayCount; j++) {
            sum += data.values[i - j][1];
        }
        result.push(+(sum / dayCount).toFixed(3));
    }
    return result;
}
export default {
    props:["code","markList"],
    data(){
        return{
            curchart : null,
            name : "",
            dataInfo : [],
        }
    },
    // inject: ['cfg',"isQry","getSleepTime","isMoneyException","addException"],
    mounted(){
        // this.initChart()
        this.getKLineInfo();
    },
    computed: {
    },
    methods:{
        
        getKLineInfo(){
            var code = this.code || "300869";
            // var code = this.code || "000997";
            var first = code.substring(0,1);
            if(code=="000001"){
                code= "1."+code;
            }else if(first=="0" || first=="3" || first=="1"){
                code = "0."+code;
            }else {
                code = "1."+code;
            }
            this.$axios.get(`http://push2his.eastmoney.com/api/qt/stock/kline/get?secid=${code}&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&ut=7eea3edcaed734bea9cbfc24409ed989&klt=101&fqt=1&beg=0&end=20500000`)
            .then((res) => {
                if (res.data.data) {
                    this.dataInfo=[];
                    var data = res.data.data;
                    this.name = data.name;
                    var len = data.klines.length;
                    if(len>100){
                        data.klines = data.klines.splice(len-100,100)
                    }
                    data.klines.map((item,idx)=>{
                        var arr = item.split(",");
                        var row = [];
                        row.push(arr[0]);//日期
                        row.push(arr[1]*1);//开
                        row.push(arr[2]*1);//收
                        row.push(arr[3]*1);//高
                        row.push(arr[4]*1);//低
                        row.push(arr[6]*1);//金额
                        row.push(arr[7]*1);//振幅
                        row.push(arr[8]*1);//涨跌幅
                        row.push(arr[9]*1);//涨跌额
                        row.push(arr[10]*1);//换手

                        this.dataInfo.push(row);
                    })
                    this.initChart();

                    //[["2004-01-02",10452.74,10409.85,10367.41,10554.96,168890000]]
                } else {
                    this.$message.error(res.data.message);
                }
            })
        },
        closeDialog(){
            this.isShowWin = false;
        },
        clearChartData(){
            var chart = this.curchart;
            if(chart){
                var option = chart.getOption();
                option.series=[];
                chart.setOption(option,true)
            }
        },
        initChart(){
            if(!this.curchart){
                const container = this.$refs.chartEl;
                if (container) {
                    this.curchart = echarts.init( container );
                }
            }
            const option = this.getChartOption();
            this.curchart.setOption(option);
        },
        getChartOption(){
            // var rawData = [["2004-01-02",10452.74,10409.85,10367.41,10554.96,168890000],
            // ["2004-01-05",10411.85,10544.07,10411.85,10575.92,221290000],["2004-01-06",10543.85,10538.66,10454.37,10584.07,191460000],
            // ["2004-01-07",10535.46,10529.03,10432,10587.55,225490000],["2004-01-08",10530.07,10592.44,10480.59,10651.99,237770000],
            // ["2004-01-09",10589.25,10458.89,10420.52,10603.48,223250000],["2004-01-12",10461.55,10485.18,10389.85,10543.03,197960000],
            // ["2004-01-13",10485.18,10427.18,10341.19,10539.25,197310000],["2004-01-14",10428.67,10538.37,10426.89,10573.85,186280000],
            // ["2004-01-15",10534.52,10553.85,10454.52,10639.03,260090000],["2004-01-16",10556.37,10600.51,10503.7,10666.88,254170000],
            // ["2004-01-20",10601.4,10528.66,10447.92,10676.96,224300000],["2004-01-21",10522.77,10623.62,10453.11,10665.7,214920000],
            // ["2004-01-22",10624.22,10623.18,10545.03,10717.4,219720000],["2004-01-23",10625.25,10568.29,10490.14,10691.77,234260000]]
            // var data = splitData(rawData);
            var data = splitData(this.dataInfo);
            var markarr = [];
            if(this.markList && this.markList.length>0){
                this.markList.map(item=>{
                    var idx = data.categoryData.findIndex((a)=>{return a==item})
                    if(idx!=-1){
                        markarr.push({name: '标记点', coord: [item, data.values[idx][2]],itemStyle:{color:"blue"}});
                    }
                })
            }
            var option = {
                title : {
                    text : this.name,
                    left: 'center',
                    align: 'right'
                },
                backgroundColor: '#fff',
                animation: false,
                legend: {
                    bottom: 10,
                    left: 'center',
                    data: ['dataline', 'MA5', 'MA10', 'MA20', 'MA30'],
                    selected: {dataline:true,MA5:false,MA10:false,MA20:false,MA30:false},
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    },
                    backgroundColor: 'rgba(245, 245, 245, 0.8)',
                    borderWidth: 1,
                    borderColor: '#ccc',
                    padding: 10,
                    textStyle: {
                        color: '#000'
                    },
                    formatter: function (params) {
                            
                        var arr = ['Date: ' + params[0].name + '<hr size=1 style="margin: 3px 0">'];
                        params.map(param=>{
                            if(param.seriesName=="dataline"){
                                arr = arr.concat([
                                    '开盘: ' + param.value[1] + '<br/>',
                                    '收盘: ' + param.value[2] + '<br/>',
                                    '最高: ' + param.value[3] + '<br/>',
                                    '最低: ' + param.value[4] + '<br/>',
                                    '振幅: ' + param.value[6] + '%<br/>',
                                    '涨跌幅: ' + param.value[7] + '%<br/>',
                                    '涨跌额: ' + param.value[8] + '<br/>',
                                    '换手: ' + param.value[9] + '%<br/>'
                                ])
                            }if(param.seriesName=="Volume"){
                                 arr.push('成交量: ' + param.value[1] + '<br/>');
                            }
                        })
                        arr.push('</hr>');
                        return arr.join('');
                    },
                    position: function (pos, params, el, elRect, size) {
                        var obj = {top: 10};
                        obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
                        return obj;
                    }
                    // extraCssText: 'width: 170px'
                },
                axisPointer: {
                    link: {xAxisIndex: 'all'},
                    label: {
                        backgroundColor: '#777'
                    }
                },
                toolbox: {
                    feature: {
                        dataZoom: {
                            yAxisIndex: false
                        },
                        brush: {
                            type: ['lineX', 'clear']
                        }
                    }
                },
                brush: {
                    xAxisIndex: 'all',
                    brushLink: 'all',
                    outOfBrush: {
                        colorAlpha: 0.1
                    }
                },
                visualMap: {
                    show: false,
                    seriesIndex: 5,
                    dimension: 2,
                    pieces: [{
                        value: 1,
                        color: downColor
                    }, {
                        value: -1,
                        color: upColor
                    }]
                },
                grid: [
                    {
                        left: '10%',
                        right: '8%',
                        height: '50%'
                    },
                    {
                        left: '10%',
                        right: '8%',
                        top: '73%',
                        height: '16%'
                    }
                ],
                xAxis: [
                    {
                        type: 'category',
                        data: data.categoryData,
                        scale: true,
                        // boundaryGap: false,
                        axisLine: {onZero: false},
                        splitLine: {show: false},
                        splitNumber: 20,
                        min: 'dataMin',
                        max: 'dataMax',
                        axisPointer: {
                            z: 100
                        }
                    },
                    {
                        type: 'category',
                        gridIndex: 1,
                        data: data.categoryData,
                        scale: true,
                        boundaryGap: false,
                        axisLine: {onZero: false},
                        axisTick: {show: false},
                        splitLine: {show: false},
                        axisLabel: {show: false},
                        splitNumber: 20,
                        min: 'dataMin',
                        max: 'dataMax'
                    }
                ],
                yAxis: [
                    {
                        scale: true,
                        splitArea: {
                            show: true
                        }
                    },
                    {
                        scale: true,
                        gridIndex: 1,
                        splitNumber: 2,
                        axisLabel: {show: false},
                        axisLine: {show: false},
                        axisTick: {show: false},
                        splitLine: {show: false}
                    }
                ],
                series: [
                    {
                        name: 'dataline',
                        type: 'candlestick',
                        data: data.values,
                        itemStyle: {
                            color: upColor,
                            color0: downColor,
                            borderColor: null,
                            borderColor0: null
                        },
                        tooltip: {
                            formatter: function (param) {
                                param = param[0];
                                return [
                                    'Date: ' + param.name + '<hr size=1 style="margin: 3px 0">',
                                    '开盘: ' + param.data[1] + '<br/>',
                                    '收盘: ' + param.data[2] + '<br/>',
                                    '最高: ' + param.data[3] + '<br/>',
                                    '最低: ' + param.data[4] + '<br/>',
                                    '振幅: ' + param.data[6] + '%<br/>',
                                    '涨跌幅: ' + param.data[7] + '%<br/>',
                                    '涨跌额: ' + param.data[8] + '<br/>',
                                    '换手: ' + param.data[9] + '%<br/>'
                                ].join('');
                            }
                        },
                        markPoint:{
                            symbol: "pin", //标注类型
                            symbolSize: 10 , //标记大小
                            data:markarr,
                            symbolOffset:[0,-3],//位置偏移
                        },
                    },
                    {
                        name: 'MA5',
                        type: 'line',
                        data: calculateMA(5, data),
                        smooth: false,
                        lineStyle: {
                            opacity: 0.5
                        }
                    },
                    {
                        name: 'MA10',
                        type: 'line',
                        data: calculateMA(10, data),
                        smooth: false,
                        lineStyle: {
                            opacity: 0.5
                        }
                    },
                    {
                        name: 'MA20',
                        type: 'line',
                        data: calculateMA(20, data),
                        smooth: false,
                        lineStyle: {
                            opacity: 0.5
                        }
                    },
                    {
                        name: 'MA30',
                        type: 'line',
                        data: calculateMA(30, data),
                        smooth: false,
                        lineStyle: {
                            opacity: 0.5
                        }
                    },
                    {
                        name: 'Volume',
                        type: 'bar',
                        xAxisIndex: 1,
                        yAxisIndex: 1,
                        data: data.volumes
                    }
                ]
            }
            return option;
        },
    }
}
</script>

<style lang="less" scope>

.kline-chart-div{
    width: 500px;
    height: 400px;
    border:1px lightgray solid;
    display: inline-block;
    margin-bottom: 5px;
    // border:1px red solid;
    .title{
        font-weight: bold;
        font-size: 15px;
        text-align: center;
        width:100%;
        margin: 5px;
    }
    .container{
        height: 400px;
        min-height: 400px;
        width:100%;
        // border: 1px red solid;
    }
    .button{
        text-align: center;
        width:100%;
        margin: 5px;
    }
}


</style>